import { loginEIP } from "@/api/public";
import {
  getToken,
  setToken,
  getUser,
  setUser,
  removeToken,
  save
} from "@/utils/auth";

const state = {
  token: getToken(),
  name: getUser(),
  roles: []
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  }
};

const actions = {
  // user login
  loginEIP({ commit }) {
    return new Promise((resolve, reject) => {
      loginEIP({
        username: window.userConfig.username,
        password: window.userConfig.password
      })
        .then(response => {
          commit("SET_TOKEN", response.token);
          commit("SET_NAME", response.username);
          setToken(response.token);
          setUser(response.username);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      removeToken();
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
